package com.yitiao.multithread;

import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.vm.VM;
public class MarkWordDemo {
    public static void main(String[] args) {
//        vmDetail();
        noLock();
        /*
         * D:\libetter\advance\JavaExpert>java -XX:+PrintFlagsInitial |grep BiasedLock
         *      intx BiasedLockingBulkRebiasThreshold          = 20                                  {product}
         *      intx BiasedLockingBulkRevokeThreshold          = 40                                  {product}
         *      intx BiasedLockingDecayTime                    = 25000                               {product}
         *      intx BiasedLockingStartupDelay                 = 4000                                {product}
         *      bool TraceBiasedLocking                        = false                               {product}
         *      bool UseBiasedLocking                          = true                                {product}
         */
        Object o = new Object();
        new Thread(()->{
            synchronized (o){
//                System.out.println(ClassLayout.parseInstance(o).toPrintable());
            }
        }).start();
        // 锁升级，先撤销再升级。
        // 那撤销后可能会升级成轻量级，也可能重新偏向另一个线程
        // 撤销的前提：当前线程执行完，没有其他字节码在执行。（即到达安全点，STW）


    }

    /**
     * 无锁演示
     * - 末尾是001
     * - hashcode占31位，只有调用时才有
     */
    private static void noLock() {
        Object o = new Object();
//        System.out.println(o.hashCode());
//        System.out.println(Integer.toHexString(o.hashCode()));
        System.out.println(ClassLayout.parseInstance(o).toPrintable());
        /*
          java.lang.Object object internals:
          OFF  SZ   TYPE DESCRIPTION               VALUE
            0   8        (object header: mark)     0x0000000000000001 (non-biasable; age: 0)
            8   4        (object header: class)    0x200001e5
           12   4        (object alignment gap)
          Instance size: 16 bytes
          Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
         */
        // 为什么类元信息是4字节？——压缩指针
    }

    private static void vmDetail() {
        // vm的详细情况
        System.out.println(VM.current().details());
        /*
          # Running 64-bit HotSpot VM.
          # Using compressed oop with 0-bit shift.
          # Using compressed klass with 3-bit shift.
          # Objects are 8 bytes aligned.
          # Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
          # Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
         */
        System.out.println(VM.current().objectAlignment());
        /*
         * 8
         */
    }
}
